import pandas as pd
from concurrent.futures import ThreadPoolExecutor
import os
import re
from io import StringIO

# 编译正则表达式模式
pattern = re.compile(r'分析结果\{([^}]*)\}')


def extract_and_process_filename(file_name_with_braces):
    match = pattern.search(file_name_with_braces)
    if match:
        content_in_braces = match.group(1).strip()
        new_content = content_in_braces.replace("非甲烷总烃", "", 1).strip() if content_in_braces.startswith("非甲烷总烃") else content_in_braces
    else:
        new_content = file_name_with_braces
    return new_content

def process_file(file_path):
    file_name, _ = os.path.splitext(os.path.basename(file_path))
    new_content = extract_and_process_filename(file_name)

    try:
        with open(file_path, 'r') as f:
            content = f.read()
        df = pd.read_csv(StringIO(content), sep='\t', header=0, dtype=str)

        df.columns = df.columns.str.strip()

        result_row = [new_content]
        for component in ['总烃', '甲烷']:
            # 检查是否存在对应组分名的行
            mask = df['组分名'].str.strip() == component
            if mask.any():
                value = df.loc[mask, '含量[mg/m3]'].squeeze()
                # 确保我们得到的是单一值
                if pd.notna(value) and isinstance(value, (int, float, str)):
                    result_row.append(f"{float(value):.4f}")
                else:
                    result_row.append("/")
            else:
                result_row.append("/")

        return result_row
    except Exception as e:
        print(f"处理文件 {file_path} 时发生错误: {e}")
        return None

def main():
    folder_path = input("请输入导出的数据文件夹路径：")
    file_list = [os.path.join(folder_path, f) for f in os.listdir(folder_path) if f.endswith('.xls')]

    summary_data = []
    with ThreadPoolExecutor() as executor:
        for result in executor.map(process_file, file_list):
            if result is not None:
                summary_data.append(result)

    summary_df = pd.DataFrame(summary_data, columns=['样品编号', '总烃', '甲烷'])
    summary_df.sort_values(by='样品编号', inplace=True)

    # 确保 DataFrame 中的数值列保持小数点后四位
    for col in ['总烃', '甲烷']:
        summary_df[col] = summary_df[col].apply(lambda x: f"{float(x):.4f}" if x != "/" else x)

    print(summary_df)
    summary_df.to_excel(os.path.join(folder_path, '汇总结果.xlsx'), index=False)

if __name__ == "__main__":
    main()